package com.jxb.myshop.dao.impl;

import com.jxb.myshop.common.Constant;
import com.jxb.myshop.dao.AddressDao;
import com.jxb.myshop.entity.Address;
import com.jxb.myshop.util.DBUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

public class AddressDaoImpl implements AddressDao {
    QueryRunner qr = new QueryRunner(DBUtil.getDs());
    @Override
    public List<Address> getUserAddress(int uid) throws SQLException {
        return qr.query("select * from address where uid = ? order by astate desc",
                new BeanListHandler<>(Address.class),
                uid);
    }

    @Override
    public int addAddress(Address add) throws SQLException {
        return qr.update("insert into address values (default,?,?,?,?,?)",
                add.getUid(),
                add.getAname(),
                add.getAphone(),
                add.getAdetail(),
                add.getAstate());
    }

    @Override
    public int deleteAddress(int aid) throws SQLException {
        return qr.update("delete from address where aid = ?",
                aid);
    }

    @Override
    public int updateAddress(Address a) throws SQLException {
        return qr.update("update address set aname = ? ,aphone= ? ,adetail= ? where aid = ?",
                a.getAname(),
                a.getAphone(),
                a.getAdetail(),
                a.getAid());
    }

    @Override
    public int setAddressNotDefault(int uid) throws SQLException {
        return qr.update("update address set astate = ? where uid = ?",
                Constant.User.NOT_DEFAULT_ADDRESS,
                uid);
    }

    @Override
    public int setAddressDefault(int aid) throws SQLException {
        return qr.update("update address set astate = ? where aid = ? ",
                Constant.User.DEFAULT_ADDRESS,
                aid);
    }
}
